<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    <link href="{{ url_for('static', path='tailwind.min.css') }}" rel="stylesheet">
    <style>
        /* 固定操作列宽度 */
        .action-cell {
            width: 150px; /* 固定操作列的宽度 */
            white-space: nowrap; /* 禁止换行 */
        }

        /* 启用水平滚动 */
        .table-container {
            overflow-x: auto; /* 启用水平滚动 */
            width: 100%;
        }

        /* 响应式布局：小屏幕隐藏部分字段 */
        @media (max-width: 768px) {
            .hide-on-mobile {
                display: none; /* 在小屏幕上隐藏 */
            }
        }

        /* 响应式布局：小屏幕折叠表格为卡片 */
        @media (max-width: 768px) {
            .responsive-table {
                display: block;
            }
            .responsive-table thead {
                display: none;
            }
            .responsive-table tbody tr {
                display: block;
                margin-bottom: 1rem;
                border: 1px solid #e5e7eb;
                border-radius: 0.5rem;
            }
            .responsive-table tbody td {
                display: block;
                text-align: right;
                padding: 0.5rem 1rem;
            }
            .responsive-table tbody td::before {
                content: attr(data-label);
                float: left;
                font-weight: bold;
                text-transform: uppercase;
            }
        }

        /* 工具提示 */
        .tooltip {
            position: relative;
            display: inline-block;
        }
        .tooltip .tooltiptext {
            visibility: hidden;
            width: 200px;
            background-color: black;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 5px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            margin-left: -100px;
            opacity: 0;
            transition: opacity 0.3s;
        }
        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }

        /* 限制字段长度 */
        .truncate-cell {
            max-width: 200px; /* 限制最大宽度 */
            white-space: nowrap; /* 禁止换行 */
            overflow: hidden; /* 超出部分隐藏 */
            text-overflow: ellipsis; /* 超出部分显示省略号 */
        }
    </style>
</head>
<body class="bg-gray-100">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-md">
        <div class="max-w-6xl mx-auto px-4">
            <div class="flex justify-between items-center py-4">
                <div class="text-lg font-semibold text-gray-800">
                    {{ system_title if system_title else "管理系统" }} <!-- 左侧标题 -->
                </div>
                <div class="flex space-x-4">
                    <a href="/" class="px-4 py-2 text-gray-700 hover:bg-gray-200 rounded-lg">首页</a>
                    {% for name, info in registered_tables.items() %}
                        <a href="/{{ name }}" class="px-4 py-2 text-gray-700 hover:bg-gray-200 rounded-lg">{{ info.table_alias }}</a>
                    {% endfor %}
                </div>
            </div>
        </div>
    </nav>

    <!-- 内容区域 -->
    <div class="p-8">
        <div class="max-w-6xl mx-auto bg-white shadow-lg rounded-lg overflow-hidden">
            <!-- 标题和搜索框 -->
            <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
                <h1 class="text-2xl font-semibold text-gray-800">{{ title }}</h1>
                <div class="flex items-center">
                    <input type="text" id="search" placeholder="搜索..." class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <button onclick="loadData()" class="ml-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">搜索</button>
                    <button onclick="openAddModal()" class="ml-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600">添加</button>
                </div>
            </div>

            <!-- 表格 -->
            <div class="table-container">
                <table class="min-w-full divide-y divide-gray-200 responsive-table">
                    <thead class="bg-gray-50">
                        <tr>
                            {% for column, alias in field_aliases.items() %}
                                {% if column != '_id' %} <!-- 排除 _id 字段 -->
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider hide-on-mobile">
                                        {{ alias }}
                                    </th>
                                {% endif %}
                            {% endfor %}
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider action-cell">操作</th>
                        </tr>
                    </thead>
                    <tbody id="table-body" class="bg-white divide-y divide-gray-200">
                        <!-- 数据通过 JavaScript 动态加载 -->
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <div class="px-6 py-4 flex justify-between items-center">
                <div id="pagination-info" class="text-sm text-gray-700"></div>
                <div class="flex space-x-2">
                    <button onclick="previousPage()" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">上一页</button>
                    <button onclick="nextPage()" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">下一页</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑模态框 -->
    <div id="modal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center">
        <div class="bg-white p-6 rounded-lg w-1/3">
            <h2 id="modal-title" class="text-xl font-semibold mb-4">添加</h2>
            <form id="modal-form" onsubmit="handleFormSubmit(event)">
                <input type="hidden" id="item-id" name="itemId">
                {% for column, alias in field_aliases.items() %}
                    {% if column != '_id' %} <!-- 排除 _id 字段 -->
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700">{{ alias }}</label>
                            <input type="text" id="{{ column }}" name="{{ column }}" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    {% endif %}
                {% endfor %}
                <div class="flex justify-end">
                    <button type="button" onclick="closeModal()" class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600">取消</button>
                    <button type="submit" class="ml-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const fieldAliases = {{ field_aliases | tojson }};
        const fieldNameList = Object.keys(fieldAliases).filter(column => column !== '_id'); // 排除 _id 字段
        const tableName = "{{ table_name }}"; // 当前表名

        let currentPage = 1;
        const limit = 10;

        // 加载数据
        async function loadData() {
            const search = document.getElementById('search').value.toLowerCase();
            try {
                const response = await fetch(`/${tableName}/api?page=${currentPage}&limit=${limit}`);
                const result = await response.json();
                const filteredData = result.data.filter(item =>
                    fieldNameList.some(column =>
                        String(item[column]).toLowerCase().includes(search)
                    )
                );
                renderTable(filteredData);
                updatePaginationInfo(result.total);
            } catch (error) {
                console.error('加载数据失败:', error);
            }
        }

        // 渲染表格
        function renderTable(data) {
            const tbody = document.getElementById('table-body');
            tbody.innerHTML = data.map(item => {
                let cells = '';
                fieldNameList.forEach(column => {
                    cells += `
                        <td data-label="${fieldAliases[column]}" class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 truncate-cell">
                            <div class="tooltip">
                                <span class="truncate">${item[column]}</span>
                                <span class="tooltiptext">${item[column]}</span>
                            </div>
                        </td>
                    `;
                });
                return `
                    <tr>
                        ${cells}
                        <td data-label="操作" class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 action-cell">
                            <button onclick="openEditModal('${item._id}')" class="px-2 py-1 bg-blue-500 text-white rounded hover:bg-blue-600">编辑</button>
                            <button onclick="confirmDelete('${item._id}')" class="px-2 py-1 bg-red-500 text-white rounded hover:bg-red-600 ml-2">删除</button>
                        </td>
                    </tr>
                `;
            }).join('');
        }

        // 更新分页信息
        function updatePaginationInfo(total) {
            const paginationInfo = document.getElementById('pagination-info');
            paginationInfo.textContent = `第 ${currentPage} 页，共 ${Math.ceil(total / limit)} 页，总计 ${total} 条数据`;
        }

        // 上一页
        function previousPage() {
            if (currentPage > 1) {
                currentPage--;
                loadData();
            }
        }

        // 下一页
        function nextPage() {
            currentPage++;
            loadData();
        }

        // 打开添加模态框
        function openAddModal() {
            document.getElementById('modal-title').textContent = '添加';
            document.getElementById('item-id').value = '';
            fieldNameList.forEach(column => {
                document.getElementById(column).value = '';
            });
            document.getElementById('modal').classList.remove('hidden');
        }

        // 打开编辑模态框
        async function openEditModal(id) {
            try {
                const response = await fetch(`/${tableName}/api/${id}`);
                const item = await response.json();
                if (item) {
                    document.getElementById('modal-title').textContent = '编辑';
                    document.getElementById('item-id').value = item._id;
                    fieldNameList.forEach(column => {
                        document.getElementById(column).value = item[column] || '';
                    });
                    document.getElementById('modal').classList.remove('hidden');
                }
            } catch (error) {
                console.error('加载数据失败:', error);
            }
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('modal').classList.add('hidden');
        }

        // 处理表单提交
        async function handleFormSubmit(event) {
            event.preventDefault();
            const id = document.getElementById('item-id').value;
            const data = {};
            fieldNameList.forEach(column => {
                data[column] = document.getElementById(column).value;
            });

            const url = id ? `/${tableName}/api/${id}` : `/${tableName}/api`;
            const method = id ? 'PUT' : 'POST';

            try {
                const response = await fetch(url, {
                    method,
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });
                if (response.ok) {
                    loadData();
                    closeModal();
                } else {
                    const error = await response.json();
                    alert(error.error || '操作失败');
                }
            } catch (error) {
                console.error('保存数据失败:', error);
            }
        }

        // 删除确认提示框
        function confirmDelete(id) {
            const isConfirmed = confirm("确定要删除这条数据吗？");
            if (isConfirmed) {
                deleteItem(id);
            }
        }

        // 删除数据
        async function deleteItem(id) {
            try {
                const response = await fetch(`/${tableName}/api/${id}`, { method: 'DELETE' });
                if (response.ok) {
                    loadData();
                }
            } catch (error) {
                console.error('删除数据失败:', error);
            }
        }

        // 初始化加载数据
        loadData();
    </script>
</body>
</html>